package com.dreamstations.changshads.fragment;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.dreamstations.changshads.R;
import com.dreamstations.changshads.adapter.DSRvAdapter;
import com.dreamstations.changshads.util.DSRequest;
import com.dreamstations.changshads.util.DSUtils;
import com.dreamstations.changshads.util.L;
import com.dreamstations.changshads.view.ListViewFooter;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.recyclerview.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

import okhttp3.internal.Util;

/**
 * 用来测试的
 */
public abstract class BaseFragmentForSection<T> extends Fragment {
    private static final String TAG = BaseFragmentForSection.class.getName();

    private DSRequest dsRequest;
    private int currentPage = 1;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;

    private DSRvAdapter<T> adapter;
    private DSRvAdapter.RvSupport header, footer;
    private DSRvAdapter.RvSupport<T> item;
    OnItemClickListener<T> onItemClickListener;
    private boolean mEnablePullLoad = false;
    private boolean mPullLoading;
    private boolean isBottom;
    private boolean mIsFooterReady = false;
    private int maxPullHeight = 80;//最多下拉高度的px值
    private int footerHeight = -1;

    private ListViewFooter mFooterView;
    private Object requestTag;

    private int tryAgainTime=0;
    private boolean isRefresh=true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFooterView=new ListViewFooter(getActivity());
        //初始化各个必要的组件
        dsRequest = getDsRequest();
        requestTag=dsRequest.getTag();
        if (requestTag==null) throw new RuntimeException("没有设置Tag！");
        item = getItem();
        header = getHeader();
        setPullLoadEnable(getmEnablePullLoad());
        onItemClickListener = getOnItemClickListener();
    }

    private void resetFooterHeight() {
        int bottomMargin = mFooterView.getBottomMargin();
        if (bottomMargin > 20) {;
            recyclerView.smoothScrollBy(0,-bottomMargin);
            //一松手就立即开始加载
            if(mIsFooterReady){
                startLoadMore();
            }
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    private void startLoadMore() {
        if(mPullLoading)return;
        mPullLoading = true;
        if(mFooterView!=null)mFooterView.setState(ListViewFooter.STATE_LOADING);
        L.i(TAG, "现在开始加载");
        mIsFooterReady = false;
        adapter.setFooter_state(adapter.FOOTER_STATE_REFRESHING);

        isRefresh=false;
        tryAgainTime=0;
        loadData(++currentPage, DSUtils.NETWORK_ELSE_CACHED);
    }
    public abstract
    @NonNull
    DSRequest getDsRequest();

    public abstract
    @NonNull
    DSRvAdapter.RvSupport<T> getItem();

    public abstract OnItemClickListener getOnItemClickListener();

    public abstract DSRvAdapter.RvSupport getHeader();

    public abstract boolean getmEnablePullLoad();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        swipeRefreshLayout = (SwipeRefreshLayout) inflater.inflate(R.layout.simple_refreshable, container, false);
        recyclerView = (RecyclerView) swipeRefreshLayout.getChildAt(1);
        initView();
        return swipeRefreshLayout;
    }

    /**
     * 设置是否开启上拉加载更多的功能
     *
     * @param enable
     */
    private void setPullLoadEnable(boolean enable) {
        mPullLoading = false;
        mEnablePullLoad = enable;
        if(mFooterView==null)return;
        if (!mEnablePullLoad) {
//            this.smoothScrollBy(0,-footerHeight);
            mFooterView.hide();
            mFooterView.setOnClickListener(null);
            mFooterView.setBottomMargin(0);
            //make sure "pull up" don't show a line in bottom when listview with one page
        } else {
            mFooterView.show();
            mFooterView.setState(ListViewFooter.STATE_LOADING);
            mFooterView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 停止loadmore
     */
    public void stopLoadMore() {
        if (mPullLoading == true) {
            mPullLoading = false;
            if(mFooterView==null)return;
            mFooterView.setState(ListViewFooter.STATE_NORMAL);
        }
    }
    private void initView() {
        //设置布局管理器
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        //设置item间隔
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, 0, 0, 16);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState){
                    case RecyclerView.SCROLL_STATE_IDLE:
                        if(isBottom)resetFooterHeight();
                        break;
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastItemPosition = layoutManager.findLastVisibleItemPosition();
                if(lastItemPosition == layoutManager.getItemCount()-1 && mEnablePullLoad) {//如果到了最后一个
                    isBottom = true;
                    mFooterView = (ListViewFooter) layoutManager.findViewByPosition(layoutManager.findLastVisibleItemPosition());//一开始还不能hide，因为hide得到最后一个可见的就不是footerview了
                    if(footerHeight==-1 && mFooterView!=null){
                        mFooterView.show();
                        mFooterView.setState(ListViewFooter.STATE_NORMAL);
                        footerHeight = mFooterView.getMeasuredHeight();//这里的测量一般不会出问题
                    }
                    updateFooterHeight(dy);
                }else if(lastItemPosition == layoutManager.getItemCount()-1 && mEnablePullLoad){//如果到了倒数第二个
                    startLoadMore();//开始加载更多
                }
                else {
                    isBottom = false;
                }
            }
        });
        adapter = new DSRvAdapter<T>(getContext(), new ArrayList<T>()
                , item);
        recyclerView.setAdapter(adapter);
        adapter.setHeader(header);

        //启用上拉加载功能
        if (mEnablePullLoad) {
            footer = new DSRvAdapter.RvSupport() {
                @Override
                public int getItemViewType(Object data) {
                    return 0;
                }

                @Override
                public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {

                    ViewHolder viewHolder=new ViewHolder(getActivity(),mFooterView,parent,-1);
                    return viewHolder;
                }

                @Override
                public void convert(ViewHolder holder, Object data) {
                }

            };
            adapter.setFooter(footer);
        }
        adapter.setOnItemClickListener(onItemClickListener);

//        填充数据
        loadData(1,DSUtils.NETWORK_ELSE_CACHED);
//        设置刷新监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                L.i(TAG, "=>onRefresh");

                stopLoadMore();
                currentPage = 1;
                isRefresh=true;
                tryAgainTime=0;
                loadData(1,DSUtils.NETWORK_ELSE_CACHED);
            }
        });
    }
    private void updateFooterHeight(float delta) {
        if(mFooterView==null)return;
        int bottomMargin = mFooterView.getBottomMargin();
        if(delta>50)delta = delta/6;
        if(delta>0) {//越往下滑越难滑
            if(bottomMargin>maxPullHeight)delta = delta*0.65f;
            else if(bottomMargin>maxPullHeight * 0.83333f)delta = delta*0.7f;
            else if(bottomMargin>maxPullHeight * 0.66667f)delta = delta*0.75f;
            else if(bottomMargin>maxPullHeight >> 1)delta = delta*0.8f;
            else if(bottomMargin>maxPullHeight * 0.33333f)delta = delta*0.85f;
            else if(bottomMargin>maxPullHeight * 0.16667F && delta > 20)delta = delta*0.2f;//如果是因为惯性向下迅速的俯冲
            else if(bottomMargin>maxPullHeight * 0.16667F)delta = delta*0.9f;
        }

        int height = mFooterView.getBottomMargin() + (int) (delta+0.5);

        if (mEnablePullLoad && !mPullLoading) {
            if (height > 50){//必须拉超过一定距离才加载更多
                mFooterView.setState(ListViewFooter.STATE_READY);
                mIsFooterReady = true;
//                Log.i("Alex2", "ready");
            } else {
                mFooterView.setState(ListViewFooter.STATE_NORMAL);
                mIsFooterReady = false;
//                Log.i("Alex2", "nomal");
            }
        }
        mFooterView.setBottomMargin(height);


    }
    /**
     * 加载数据到item
     *
     * @param page      页码
     * @param cacheType CACHE还是NETWORK
     */
    private void loadData(final int page, int cacheType) {
        DSUtils.getInstance().cancelByTag(requestTag);
        dsRequest
                .addParams("page", String.valueOf(page))
                .cacheType(cacheType)
                .build()
                .execute(new DSRequest.DSCallback<List<T>>() {
                    @Override
                    public void onResponse(List<T> result) {
                        if (adapter==null) return;
                        if(isRefresh) {
                            adapter.setItemDatas(result);
                            isRefresh=false;
                        }else {
                            adapter.addMoreItemData(result);
                            stopLoadMore();
                        }
                        if (swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
//                        Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                        Log.w(TAG, "=>loadData:" + msg);
                        if (swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                        if (tryAgainTime<3){
                            loadData(page,DSUtils.NETWORK_ELSE_CACHED);
                            tryAgainTime++;
                            L.w(TAG,"=>loadData:tryAgain:"+tryAgainTime);
                        }else {
                            if(!isRefresh){
                                stopLoadMore();
                            }
                            if(getActivity()!=null) {
                                Toast.makeText(getActivity().getApplicationContext(), "没有更多数据", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });

    }
    @Override
    public void onPause() {
        DSUtils.getInstance().cancelByTag(requestTag);
        super.onPause();
    }
}

